$(document).ready(function () {

    initSubMenu();
    queryTable();


    layui.use(function () {

        var layer = layui.layer;

        laydate = layui.laydate;

        // 表格
        form = layui.form;
        form.on('select(needCharge)', function (data) {//监听是否充电查询条件下拉
            $('div[lay-filter="search"]').click();
        });
        form.on('select(searchType)', function (data) {//监听是否充电查询条件下拉
            $('div[lay-filter="search"]').click();
        });

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable()
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            var p = {};
            p.name = data.field.planName
            p.type = data.field.planType


            const resultArray = $('.form-plan-item').map(function () {
                const $item = $(this);
                return {
                    seqNo: $item.find('input[name="seqNo"]').val() || 0,
                    name: $item.find('input[name="name"]').val() || '',
                    manageType: $item.find('select[name="manageType"]').val() || '',
                    content: $item.find('input[name="content"]').val() || ''
                };
            }).get();

            p.items = resultArray

            new AjaxChain()
                .setUrl('/work/plan/add')
                .setMethod('post')
                .setData(JSON.stringify(p))
                .then(data => {
                    layer.close(drawer);
                    layer.msg('新增成功', { icon: 1, time: 2000 });

                    queryTable()
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


            return false;
        });

    });
})
var params = {};//查询条件参数
var form, unit, laydate;
var drawer;//抽屉实例
var curId = null;//当前选中用户ID
var typeStr = '';//用户类型集合


// 查询表格数据
queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 240
    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/work/plan/list/page"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: params
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                { field: 'name', title: '计划名称', align: "center" }
                , { field: 'typeDesc', title: '周期类型', align: "center" }
                , { field: 'createTime', title: '创建时间', align: "center" }
                , {
                    field: 'updateTime', title: '更新时间', align: "center",
                }
                , {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: toolWidth,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool">
                                <div onclick='showMore("${d.id}")' class="table-edit layui-btn">
                                  <img src="../static/img/edit.png">编辑
                                </div>
                                <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                                  <img src="../static/img/del.png">删除
                                </div>
                              </div>`;
                    },
                },
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

    });
}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openDrawer(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/work/plan/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            openDrawer(1)
            break;

        default:
            break;
    }
}



openDrawer = () => {

    drawer = layer.open({
        title: '新增计划',
        type: 1,
        area: ['70%', '70%'],
        shade: 0.3,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {

            $('select[name="manageType"]').html(new ST().manageType())

            form.render(null, 'editForm');

            $('.layui-icon-add-circle').click(function () {
                $('#add-form').append(
                    `<div class="form-item layui-col-xs12 layui-padding-1 form-plan-item">
                            <div class="form-item layui-col-xs2 layui-padding-1">
                                    <input type="text" name="seqNo" lay-affix="clear" placeholder="序号"
                                        class="layui-input">
                            </div>
                            <div class="form-item layui-col-xs3 layui-padding-1">
                                    <input type="text" name="name" lay-affix="clear" placeholder="计划项名称" lay-verify="required"
                                        class="layui-input">
                            </div>
                            <div class="form-item layui-col-xs2 layui-padding-1">
                                    <select name="manageType" lay-filter="" >
                                    ${new ST().manageType()}
                                    </select>
                            </div>
                            <div class="form-item layui-col-xs4 layui-padding-1">
                                    <input type="text" name="content" lay-affix="clear" placeholder="详细记录" 
                                        class="layui-input">
                            </div>
                            <div class="form-item layui-col-xs1 layui-padding-1">
                                <div class="form-layui-icon">
                                    <i class="layui-icon layui-icon-reduce-circle" onclick=removeItem(this)></i>
                                </div>
                            </div>
                        </div>`
                )
                form.render(null, 'editForm');

            })

        },
        content: $("#save-templet").html()
    });

}

function removeItem(t) {
    $(t).parent().parent().parent().remove()
}




// 查看更多

function showMore(planId) {

    layer.open({
        type: 1, // page 层类型
        area: ['80%', '70%'],
        title: `<div style="height: 100%;display: flex;align-items: center;justify-content: space-between;">
                    计划项信息
                    <div class="table-edit layui-btn" onclick=addNewNodes("${planId}")> 
                        新增计划项
                    </div>
                </div>`,
        move: false,
        shade: 0.6, // 遮罩透明度
        shadeClose: true, // 点击遮罩区域，关闭弹层
        maxmin: false, // 允许全屏最小化
        anim: 0, // 0-6 的动画形式，-1 不开启
        content: `<div style="width: 100%;height: 100%;display: flex;padding: 0.2rem;"><table id="table-item" lay-filter="table-item" style="width: 100%;height: 100%;"></table></div>`,
        success: function () {
            queryItemTable(planId)
        }
    });

}
//新增环节弹窗
addNewNodes = (id) => {

    layer.open({
        type: 1,
        area: '40%',
        offset: ['20%'],
        resize: false,
        shadeClose: true,
        title: "新增计划项",
        content: `<form class="layui-form layui-form-pane" id="node-form" lay-filter="nodeForm" action="">
                    <div class="form-item">
                        <label class="layui-form-label">序号</label>
                        <div class="layui-input-block">
                            <input type="text" name="seqNo" lay-affix="clear" lay-verify="required" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">计划项名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" lay-affix="clear" lay-verify="required" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">主要负责人</label>
                        <div class="layui-input-block">
                        <select name="manageType">
                            ${new ST().manageType()}
                        </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">详细记录</label>
                        <div class="layui-input-block">
                            <input type="text" name="content" lay-affix="clear" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool">
                        <div class="layui-btn layui-edit-submit" lay-submit  lay-filter="node-edit">确认</div>
                    </div>
                </form>`,
        success: function (layero, index, that) {
            form.render();

            // form.val('nodeForm', res);

            form.on('submit(node-edit)', function (data) {
                
                var field = data.field;

                field.planId = id;

                saveNode(field, index)

                return false;
            });
        },
    });

}


// 保存环节信息接口
saveNode = (params, index) => {
    new AjaxChain()
        .setUrl('/work/plan/item/add')
        .setMethod('post')
        .setData(JSON.stringify(
            params
        ))
        .then(data => {
            if (index) {
                layer.close(index);
            }

            layer.msg('新增成功', { icon: 1, time: 2000 });
            queryItemTable(params.planId)
        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();
}




// 查询表格数据
queryItemTable = (planId) => {


    layui.use('table', function () {

        var table = layui.table;
        //展示已知数据
        table.render({
            elem: '#table-item'
            , text: {
                none: '暂无数据'
            }
            , url: ajaxPrefix() + "/work/plan/item/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: {
                planId: planId,
                pageSize: 10
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "data": res.result //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                { field: 'seqNo', title: '排序', align: "center" }
                , { field: 'name', title: '计划项名称', align: "center" }
                , { field: 'manageTypeDesc', title: '主要负责人', align: "center" }
                , { field: 'content', title: '详细记录', align: "center" }
                , { field: 'createTime', title: '创建时间', align: "center" }
                , { field: 'updateTime', title: '修改时间', align: "center" }
                , {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: 120,
                    templet: function (d) {
                        return `<div class="table-tool">
                                <div onclick='delItem("${d.id}","${d.planId}")' class="table-del layui-btn">
                                  <img src="../static/img/del.png">删除
                                </div>
                              </div>`;
                    },
                },
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: false
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('#table-item').height() / 20);
            },

        });

    });
}



function delItem(id, planId) {
    layer.confirm('确定删除该项吗？', { icon: 3 }, function () {

        new AjaxChain()
            .setUrl('/work/plan/item/delete')
            .setData({ id: id })
            .then(data => {
                layer.msg('删除成功', { icon: 1, time: 1500 });
                queryItemTable(planId);
            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();
    });
}